package firehwak.thoth.client.service;

import firehwak.thoth.client.database.LocalDatabase;
import firehwak.thoth.client.location.LocationHelper;
import firehwak.thoth.client.phonestate.MyPhoneStateListener;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class ThothService extends Service implements Runnable {
	private boolean running = false;

	public void run() {
		if (!running) return;

		locationHelper.Start();
		telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

		threadHandler.postDelayed(this, 1 * 60 * 1000);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		threadHandler = new Handler();
		running = true;

		initializeLocation();
		initializeSignalStrength();
		initializeDatabase();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		threadHandler.post(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		locationHelper.Stop();
		telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

		running = false;
	}

	private Handler threadHandler;

	private LocationHelper locationHelper;

	private void initializeLocation() {
		locationHelper = new LocationHelper((LocationManager) getSystemService(Context.LOCATION_SERVICE),
			new LocationHelper.CustomLocationListener() {
				public void onLocationUpdate() {
					updateLocation();
				}
			});
	}

	private void updateLocation() {
		Location location = locationHelper.getLocation();
		locationHelper.Stop();
		
		//if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)) return;

		int signalStrength = phoneStateListener.getSignalStrength();
		telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);

		database.insertData(location.getLatitude(), location.getLongitude(), signalStrength);

		String text = String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()) + " "
				+ String.valueOf(signalStrength);
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

	// SignalStrength
	private TelephonyManager telephonyManager;
	private MyPhoneStateListener phoneStateListener;

	private void initializeSignalStrength() {
		phoneStateListener = new MyPhoneStateListener();
		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	}

	LocalDatabase database;

	private void initializeDatabase() {
		database = new LocalDatabase(this);
		database.open();
	}
}
